#!/usr/bin/perl -w

use strict;
use warnings;

#1. create the index of entries
my %index;
my $counter = 0;
open (my $HIN, "<",$ARGV[0]);
while(<$HIN>){
    chop;
    if ($_ =~ /^Name:(.*)/){
	my $pepName = $1;
	$pepName =~ s/^\s*//;
	$pepName =~ s/\s*$//;
	if (exists $index{$pepName}){
	    die "ERROR: $1 NOT unique spectrum! Please use consensused library\n";
	}else{	   
	    $index{$pepName} = tell();
	    $counter ++;
	    if (($counter % 1000) == 0){
		print STDERR "$counter...";
	    }
	}
    }
}
&println;


if(0){
    
    foreach (sort keys %index){
	print $_."=".$index{$_};&println;
    }
    print scalar(keys %index);
    &println;
}

print "pepName\ttotalInten\tassigedInten\tassignedIntenFraction\ttoalPeaksNum\tassignedOPeaksNum\tassingedPeaksNumFraction\n";
foreach (sort keys %index){
    my $totalIntensity = 0;
    my $assignedIntensity = 0;
    my $totalPeaksNum = 0;
    my $assignedPeaksNum = 0;
    my $key = $_;#key is peptide name
    seek($HIN,$index{$key},0);
    while(<$HIN>){
	if ($_ =~ /^([\d\.]+)\s([\d\.]+)\s([^\s]+)\s/){
	    $totalIntensity += $2;
	    $totalPeaksNum ++;
	    if ($3 eq "?"){
		#do nothing
	    }else{
		#annotated/assigned
		$assignedIntensity += $2;
		$assignedPeaksNum ++;
	    }
	}elsif ($_ =~ /^Name/){
	    last;
	}
    }
    my $assignedIntenFraction = $assignedIntensity /$totalIntensity; 
    my $assignedPeaksNumFraction = $assignedPeaksNum / $totalPeaksNum;
    print $key."\t".$totalIntensity."\t".$assignedIntensity."\t".$assignedIntenFraction."\t".$totalPeaksNum."\t".$assignedPeaksNum."\t".$assignedPeaksNumFraction."\n";
}
close $HIN;

sub println (){
    print "\n";
}
